package com.bw.order.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.order.to.UserTo;
import com.bw.order.utils.GetCookieUtil;
import com.bw.order.vo.HouseUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.bw.order.entity.HouseRentOrderEntity;
import com.bw.order.service.HouseRentOrderService;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.R;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


/**
 * 租房订单表
 *
 * @author Hao_YunKai
 * @email 2745578447@qq.com
 * @date 2022-03-23 16:04:29
 */
@RestController
@RequestMapping("order/house-rent-order")
public class HouseRentOrderController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HouseRentOrderService houseRentOrderService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = houseRentOrderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{rentOid}")
    public R info(@PathVariable("rentOid") Long rentOid){
		HouseRentOrderEntity houseRentOrder = houseRentOrderService.getById(rentOid);

        return R.ok().put("houseRentOrder", houseRentOrder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestParam Map<String, Object> params){
		houseRentOrderService.add(params);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody HouseRentOrderEntity houseRentOrder){
		houseRentOrderService.updateById(houseRentOrder);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] rentOids){
		houseRentOrderService.removeByIds(Arrays.asList(rentOids));

        return R.ok();
    }
    @RequestMapping("getUrl")
    public R getUrl(@RequestParam Map<String, Object> params){
        String id = (String) params.get("id");
        String uids = (String) params.get("uuid");
        String uuid = UUID.randomUUID().toString().replace("-","");
        String s = null;
        try {
            s = redisTemplate.opsForValue().get(uids);
        } catch (Exception e) {
            System.out.println("登录失效");
            return R.error(403,"登录失效");
        }
        if (s!=null && !s.equals("")){
            HouseUserVo vo = JSONObject.parseObject(s, new TypeReference<HouseUserVo>() {
            });
            redisTemplate.opsForValue().set(uuid+vo.getUserPhone(),id+"",5, TimeUnit.MINUTES);
            return R.ok().put("uuids",uuid);
        }  else {
            return R.error(403,"登录失效");
        }
    }

    // 查询当前用户的订单
    @GetMapping("findOrderByUser")
    public R findOrderByUser() {
        String token = getCookie("token");
        if (StringUtils.isNotBlank(token)) {
            String s = redisTemplate.opsForValue().get(token);
            UserTo user = JSON.parseObject(s, new TypeReference<UserTo>(){});
            QueryWrapper<HouseRentOrderEntity> wrapper = new QueryWrapper<>();
            assert user != null;
            wrapper.eq("user_phone",user.getUserPhone());
            List<HouseRentOrderEntity> list = houseRentOrderService.list(wrapper);
            return R.ok().put("list",list);
        }
        return R.error();
    }

    private String getCookie(String cookieKey) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookieKey.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }

}
